﻿using System.Collections.Generic;
using Newtonsoft.Json;

namespace HBFramework
{
    /// <summary>
    /// 存档管理
    /// </summary>
    public class StorageManager : Singleton<StorageManager>, ISingleton, ISingletonUpdate
    {
        private IStorageBehaviour storageBehaviour;
        private Dictionary<string, BaseStorage> storageDict;

        public int Order => 100;

        public void OnInit()
        {
#if UNITY_EDITOR
            storageBehaviour = new StorageBehaviour_Normal();
#elif UNITY_WECHAT_GAME
            storageBehaviour = new StorageBehaviour_WxMiniGame();
#else
            storageBehaviour = new StorageBehaviour_Normal();
#endif
            storageBehaviour.Init();
            storageDict = new Dictionary<string, BaseStorage>();
        }

        public void OnUpdate()
        {
            storageBehaviour.Update();
        }

        public void OnDestroy()
        {

        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetStorage<T>() where T : BaseStorage, new()
        {
            string key = typeof(T).Name;
            if (storageDict.ContainsKey(key))
            {
                return storageDict[key] as T;
            }
            var json = storageBehaviour.GetDataString(key);
            if (!string.IsNullOrEmpty(json))
            {
                var storage = JsonConvert.DeserializeObject<T>(json);
                storageDict.Add(key, storage);
                return storage;
            }
            else
            {
                var storage = new T();
                storage = storage.GetDefaultValue<T>();
                storageDict.Add(key, storage);
                return storage;
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void SaveStorage<T>()
        {
            var key = typeof(T).Name;
            var storage = storageDict[key];
            string json = JsonConvert.SerializeObject(storage);
            storageBehaviour.SetDataString(key, json);
        }

        /// <summary>
        /// 清理存档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void ClearStorage<T>()
        {
            var key = typeof(T).Name;
            if (storageDict.ContainsKey(key))
            {
                storageDict.Remove(key);
            }
            storageBehaviour.ClearAll();
        }

        /// <summary>
        /// 清除所有存档
        /// </summary>
        public void ClearAllStorage()
        {
            storageBehaviour.ClearAll();
#if UNITY_EDITOR
            UnityEditor.EditorApplication.ExitPlaymode();
#else
            UnityEngine.Application.Quit();
#endif
        }
    }
}